package com.xyh.web.servlet;

import com.xyh.web.context.ApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * 1、Tomcat在启动的时候，会为每一个Servlet创建对象
 * 2、Tomcat自然会给DispatcherServlet (tomcat保证的单实例)创建对象
 * 3、DispatcherServlet一定会初始化，整个初始化调用过来以后就会启动ioc容器
 */
public class DispatcherServlet extends HttpServlet {
    private ApplicationContext applicationContext;

    public DispatcherServlet() {
        System.out.println("DispatcherServlet");
    }

    public DispatcherServlet(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

	@Override
	public void init() throws ServletException {
		System.out.println("DispatcherServlet.init");
		this.applicationContext = initWebApplicationContext();
	}

	private ApplicationContext initWebApplicationContext() {
		ServletContext servletContext = getServletContext();
		Enumeration<String> attributeNames = servletContext.getAttributeNames();
		System.out.println("attributeNames");
		while (attributeNames.hasMoreElements()) {
			System.out.println(attributeNames.nextElement());
		}
		//先会获取之前的 WebApplicationContext（构建父子容器）
		ApplicationContext rootContext = (ApplicationContext) servletContext.getAttribute(ApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		ApplicationContext wac = null;
		if (this.applicationContext != null) {
			wac = this.applicationContext; //当前的web-ioc容器;
			if (wac.getParent() == null) {
				wac.setParent(rootContext); //父子容器的体现，
			}
			configureAndRefreshWebApplicationContext(wac);
			wac.refresh();
		}
		return wac;
	}

	private void configureAndRefreshWebApplicationContext(ApplicationContext wac) {
		wac.setServletContext(getServletContext());
	}

	@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("访问。。。"+req.getRequestURI());
		System.out.println(applicationContext);
    }
}
